2
2
.
.
3
3
.
.
4
4
S
S
t
t
a
a
t
t
e
e
m
m
e
e
n
n
t
t
s
s
-
-
L
L
o
o
o
o
p
p
I
I
n
n
f
f
o
o
[
[
R
R
]
]
Loop Statements execute its Body multiple times (while condition is TRUE or while iterating through Elements)
● for…in Statement iterates through Sequence or Array Elements and executes its Body for each Element.
● while Statement executes its Body while condition is TRUE. Condition is checked at the beginning of Body
● do .. while Statement executes its Body while condition is TRUE. Condition is checked at the end of Body.
You can use
● break Jump Statement to exit Loop Statement
● continue Jump Statement to skip rest of the Body and continue with next iteration from the beginning of Body
f
f
o
o
r
r
…
…
i
i
n
n
for…in can be used to iterate through Elements of Sequence or Array.
Iterate through Sequence Elements
for (i in 1..5 ) { println(i) } // 1 2 3 4 5
for (i in 1..5 step 2) { println(i) } // 1 3 5
for (i in 6 downTo 0 step 2) { println(i) } // 6 4 2 0
Iterate through Array Elements
val people = arrayOf("John", "Lucy", "Bob") // DECLARE ARRAY
for (person in people ) { println(person) } // John Lucy Bob
for (index in people.indices ) { println(people[index]) } // John Lucy Bob
for ((index, value) in people.withIndex()) { println("$index = $value") } // 0 = John, 1 = Lucy, 2 = Bob
w
w
h
h
i
i
l
l
e
e
while checks conditions at the beginning of the Body.
while
var i = 0
while(i < 5) {
i++
println(i)
}
d
d
o
o
.
.
.
.
w
w
h
h
i
i
l
l
e
e
do .. while checks conditions at the end of the Body.
do .. while
var i = 0
do {
i++
println(i)
} while(i < 5)